﻿using CommonTools;
using shop.Bll.BasicInfo;
using shop.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace shop.Logi
{
    public partial class LogisticsFeeConfigItemEditDialog : Form, IEditItemDialog<LogisticsFeeConfigItem>
    {

        public LogisticsFeeConfigItem Item { set; get; }
        shop.Bll.LogisticsFeeConfigBll _bll = new Bll.LogisticsFeeConfigBll();

        //List<LogiFeeConfigStockItem> _stocks = null;
        IEnumerable<LogiInfo> _logis = null;


        public LogisticsFeeConfigItemEditDialog()
        {
            InitializeComponent();
            //this.box_OccurDate.Value = DateTime.Today;

        }

        private void btn_cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private async void btnOk_Click(object sender, EventArgs e)
        {
            if (Item == null)
            {
                Item = new LogisticsFeeConfigItem();
            }

            //if (box_OccurDate.Value== null)
            //{
            //    MessageBox.Show("日期不能为空", Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    return;
            //}


            Item.ReportGroup = box_ReportGroup.Text.Trim();
            Item.Method = box_Method.Text.Trim();
            //Item.LogiAccount = box_LogiAccount.Text.Trim();
            //Item.Stock = box_Stock.Text.Trim();
            Item.ShareAmount = box_ShareAmount.Value;
            Item.MinQty = box_MinQty.Value;
            Item.MaxQty = box_MaxQty.Value;
            Item.AddPrice = box_AddPrice.Value;
            Item.Enable = box_enable.Checked;
            Item.NoOutstock = box_noOutstock.Checked;

            if (Item.AcctItems == null) Item.AcctItems = new List<LogiFeeConfigAcctItem>();
            if (Item.StockItems == null) Item.StockItems = new List<LogiFeeConfigStockItem>();

            Item.AcctItems.Clear();
            foreach (DataGridViewRow item in grid_logAcct.Rows)
            {
                if (item.IsNewRow) break;
                if (item.Cells[cl_selected.Index].Value.IsNull(false) == true
                    && string.IsNullOrEmpty( item.Cells[cl_logiAcct.Index].Value?.ToString()) == false)
                {
                    Item.AcctItems.Add(new LogiFeeConfigAcctItem() { LogiAcct = item.Cells[cl_logiAcct.Index].Value?.ToString() });
                }
            }

            Item.StockItems.Clear();
            foreach (DataGridViewRow item in grid_stock.Rows)
            {
                if (item.IsNewRow) break;
                Item.StockItems.Add(new LogiFeeConfigStockItem() { Stock = item.Cells[cl_ck.Index].Value?.ToString() });
            }

            Result res = await _bll.SaveItem(Item);

            if (res.ErrorCode != ResultCode.Ok)
            {
                MessageBox.Show(res.Message, Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information); 
                return;
            }


            this.DialogResult = DialogResult.OK;
            this.Close();

        }


        private async void FuturesBuyEditDialog_Load(object sender, EventArgs e)
        {
            // 所有仓库
            _logis = await new LogiInfoBll().QueryLaoban(null);
            //var items = _logis.Select(a => new { bl = false, logi = a.LogiAcct }).ToList();

            this.grid_logAcct.AddItems(_logis, a=> false, a => a.LogiAcct);



            if (Item != null)
            {
                box_ReportGroup.Text = Item.ReportGroup;
                box_Method.Text = Item.Method;
                //box_LogiAccount.Text = Item.LogiAccount;
                //box_Stock.Text = Item.Stock;
                box_ShareAmount.Value = Item.ShareAmount;
                box_MinQty.Value = Item.MinQty;
                box_MaxQty.Value = Item.MaxQty;
                box_AddPrice.Value = Item.AddPrice;
                box_FUser.Text = Item.FUser;
                box_enable.Checked = Item.Enable;
                box_noOutstock.Checked = Item.NoOutstock;

                //var stockItems = await _bll.GetSotckItems(Item.id);
                //this.grid_stock.AddItems(stockItems, a => a.Stock);

       
                var logiItems = await _bll.GetAcctItems(Item.id);
                //this.grid_logAcct.AddItems(logiItems, a=> a.LogiAcct);
                foreach (DataGridViewRow row in grid_logAcct.Rows)
                {
                    var item = row.Cells[cl_logiAcct.Index].Value?.ToString();
                    if (string.IsNullOrEmpty(item) == false && logiItems.Any(a => a.LogiAcct == item))
                    {
                        row.Cells[cl_selected.Index].Value = true;
                    }
                }



            }
            else
            {
                box_enable.Checked = true;
            }
        }

        private async void btn_delete_Click(object sender, EventArgs e)
        {
            if (Item == null || Item.id <=0 )
            {
                MessageBox.Show("不能执行此操作", Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var res = await _bll.DeleteItem(Item.id);

            if (res.ErrorCode != ResultCode.Ok)
            {
                MessageBox.Show(res.Message, Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }


            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void box_LogiAccount_RequestValidate(CommonTools.Controls.FastTextBox arg1, CommonTools.Controls.FastValueArgs arg2)
        {
            //if(arg2.ChangeMode == CommonTools.Controls.ChangeModeEnum.Clear)
            //{
            //    return;
            //}


            //var bll = new LogiInfoBll();
            //var col = new Dictionary<string, string>()
            //{
            //    {nameof(LogiInfo.LogiAcct),"快递账户" },
            //    {nameof(LogiInfo.IsAgent),"是否代发" },
            //    {nameof(LogiInfo.logistics_name),"快递名称" },
            //    //{nameof(LogiInfo.logistics_name),"快递名称" },
            //};

            //var res = await new Selector<LogiInfo>()
            //  .UseSearchAsync(a => bll.Query(a.FirstOrDefault()))
            //  .UseColumns(col)
            //  .FindText(this.box_LogiAccount.Text.Trim())
            //  .GetValueAsync();

            //if (res.IsOk)
            //{
            //    arg1.Text = res.Data.LogiAcct;
            //}
            //else
            //{
            //    //arg1.Text = string.Empty;
            //}
        }

        private void grid_logAcct_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if(e.ColumnIndex<0 || e.RowIndex< 0)
            {
                return;
            }

            if (e.ColumnIndex == cl_logiAcct.Index)
            {
                GetLogi(e.RowIndex, grid_logAcct[e.ColumnIndex, e.RowIndex].Value.IsNull(), false);
            }

        }



        private async void GetLogi(int rowIndex, string arg2, bool isKey)
        {
            if (string.IsNullOrEmpty(arg2) && !isKey) //内容空的, 直接退出
            {
                //将单据内容关联属性清空
                grid_logAcct[cl_logiAcct.Index, rowIndex].Value = string.Empty;

                return;
            }

            var bll = new LogiInfoBll();
            var col = new Dictionary<string, string>()
            {
                {nameof(LogiInfo.LogiAcct),"快递老板" },
                //{nameof(LogiInfo.IsAgent),"是否代发" },
                //{nameof(LogiInfo.logistics_name),"快递名称" },
                //{nameof(LogiInfo.logistics_name),"快递名称" },
            };

            var res = await new Selector<LogiInfo>()
                .UseSearchAsync(a => bll.QueryLaoban(a.FirstOrDefault()))
                .UseColumns(col)
                .FindText(arg2)
                .GetValueAsync();

            if (res.IsOk)
            {
                grid_logAcct[cl_logiAcct.Index, rowIndex].Value = res.Data.LogiAcct;
            }
            else
            {
                grid_logAcct[cl_logiAcct.Index, rowIndex].Value = string.Empty;
            }
        }

        private void grid_logAcct_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.Cancel = true;
        }

        private void box_findLogi_RequestValidate(CommonTools.Controls.GuanTextBox arg1, CommonTools.Controls.FastValueArgs arg2)
        {
            if(this.grid_logAcct.Rows.Count ==0 || _logis == null)
            {
                return;
            }

            if (string.IsNullOrEmpty(arg1.Text?.Trim()))
            {
                //this.grid_logAcct.Rows.Clear();
                //this.grid_logAcct.AddItems(_logis, a => a.LogiAcct);
                return;
            }
            grid_logAcct.ClearSelection();

            grid_logAcct.SearchString(arg1.Text.Trim());
            if (grid_logAcct.SearchResultList?.Any() == true)
            {
                grid_logAcct[cl_logiAcct.Index, grid_logAcct.SearchResultList[0].RowIndex].Selected = true;

                //如果这个单元格没有显示在屏幕上, 滚动gridview
                if (this.grid_logAcct.SearchResultList[0].Displayed == false)
                    this.grid_logAcct.FirstDisplayedCell = this.grid_logAcct.SearchResultList[0];

            }

            //foreach (DataGridViewRow item in grid_logAcct.Rows)
            //{
            //}
            //var find = arg1.Text.Trim();

            //var list = _logis.Where(a => a.LogiAcct.Contains(find)).ToList();

            //this.grid_logAcct.Rows.Clear();
            //this.grid_logAcct.AddItems(list, a => a.LogiAcct);
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            var items = new List<string>();

            foreach (DataGridViewRow row in grid_logAcct.Rows)
            {
                if (row.Cells[cl_selected.Index].Value.IsNull(false) == true)
                {
                    items.Add(row.Cells[cl_logiAcct.Index].Value?.ToString());
                }
            }

            if (checkBox1.Checked)
            {
                // 只显示选中内容
                grid_logAcct.Rows.Clear();
                grid_logAcct.AddItems(items, a => true, a => a);
            }
            else
            {
                grid_logAcct.Rows.Clear();
                grid_logAcct.AddItems(_logis, a => false, a => a.LogiAcct);

                foreach (DataGridViewRow row in grid_logAcct.Rows)
                {
                    var item = row.Cells[cl_logiAcct.Index].Value?.ToString();
                    if (string.IsNullOrEmpty(item) == false && items.Contains(item))
                    {
                        row.Cells[cl_selected.Index].Value = true;
                    }
                }
            }

        }

        //private void box_findStock_RequestValidate(CommonTools.Controls.GuanTextBox arg1, CommonTools.Controls.FastValueArgs arg2)
        //{
        //if (this.grid_stock.Rows.Count == 0 || _stocks == null)
        //{
        //    return;
        //}

        //if (string.IsNullOrEmpty(arg1.Text?.Trim()))
        //{
        //    this.grid_stock.Rows.Clear();
        //    this.grid_stock.AddItems(_stocks, a => a.Stock);
        //    return;
        //}


        //var find = arg1.Text.Trim();

        //var list = _stocks.Where(a => a.Stock.Contains(find)).ToList();

        //this.grid_logAcct.Rows.Clear();
        //this.grid_logAcct.AddItems(list, a => a.Stock);

        //}
    }
}
